﻿using AutoMapper;
using Blog.Core.Domain.Model.User;
using Blog.Core.DTO;
using Blog.Core.DTO.ViewModel;
using Blog.Core.DTO.ViewModel.User;
using Blog.Core.IRepositories;
using Blog.Core.IRepositories.IUser;
using Blog.Core.IServices.IUser;
using Blog.Core.Repositories.User;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace Blog.Core.Services.User
{
    /// <summary>
    /// 角色信息服务
    /// </summary>
    public class RolesService: BaseService<Roles>,IRolesServices
    {
        private readonly IUserInfoRepository userInfoRepositories;//用户
        private readonly IRoleUserRepository userRepository;//用户和角色
        private readonly IRolesRepository rolesRepositories;//角色
        private readonly IPermissionsRepository permissionsRepository;//权限
        private readonly IRolePermissionRepository rolePermissionRepository;//角色和权限
        private readonly IUnOfWork unOfWork;

        public RolesService(IRepository<Roles> repository, IUserInfoRepository userInfoRepositories, IRoleUserRepository userRepository, IPermissionsRepository permissionsRepository, IRolesRepository rolesRepositories, IRolePermissionRepository rolePermissionRepository, IUnOfWork unOfWork) : base(repository, unOfWork)
        {
            this.userInfoRepositories = userInfoRepositories;
            this.userRepository = userRepository;
            this.rolesRepositories = rolesRepositories;
            this.permissionsRepository = permissionsRepository;
            this.rolePermissionRepository = rolePermissionRepository;
            this.unOfWork = unOfWork;
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public async Task<PageDTO<GetRolePowerDTO>> GetRoleInfo(string name,int pageindex, int pagesize)
        {
            var rolePermission = await rolePermissionRepository.GetAll();
            var permissions = await permissionsRepository.GetAll(); 
            var list = from x in await rolesRepositories.GetAll()
                       where x.Delete==0
                       select new GetRolePowerDTO
                       {
                           Id = x.Id,
                           RoleName = x.RoleName,
                           RoleDescription = x.RoleDescription,
                           RoleStart = x.RoleStart,
                           Delete= x.Delete,
                           CreateName= x.CreateName,
                           CreateTime= x.CreateTime,
                           UpdateName= x.UpdateName,
                           UpdateTime= x.UpdateTime,
                           PermissionsNames = (from y in rolePermission
                                               join z in permissions on y.PermissionId equals z.Id
                                               where y.RoleId.Equals(x.Id)
                                               select new GetRolePowerItemDTO
                                               {
                                                   PermissionsName = z.PermissionsName
                                               }).ToList(),

                       };
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(x => x.RoleName.Contains(name) && x.Delete == 0);
            }
            PageDTO<GetRolePowerDTO> data = new PageDTO<GetRolePowerDTO>
            {
                RecordCount = list.Count(),
                Plist = list.OrderBy(m => m.Id).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList(),
            };

            return data;

        }
        /// <summary>
        /// 批量修改角色状态
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResponseResultDTO<int>> PutRole(string ids)
        {
            //定义一个数组
            string[] arr = ids.Split(',');
            //遍历
            foreach (var m in arr)
            {
                //转为int
                var id = Convert.ToInt32(m);
                var obj = await rolesRepositories.GetById(id);
                if (obj.RoleStart == false)
                {
                    obj.RoleStart = true;
                }
                else if (obj.RoleStart == true)
                {
                    obj.RoleStart = false;
                }
                await rolesRepositories.Update(obj);
                await unOfWork.SaveChanges();
            }
            return new ResponseResultDTO<int>()
            {
                Data = arr.Length,
                Message = "修改成功！",
                Code = ResultStatusCode.SUCCESS,
            };
        }
        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ResponseResultDTO<int>> DelectRole(string ids)
        {
            //定义一个数组
            string[] arr = ids.Split(',');
            //遍历
            foreach (var m in arr)
            {
                //转为int
                var id = Convert.ToInt32(m);
                var obj = await rolesRepositories.GetById(id);
                if (obj != null)
                {
                    obj.Delete = 2;
                }
                await rolesRepositories.Update(obj);

                var list = await rolePermissionRepository.GetAll();
                list = list.Where(n => n.RoleId.Equals(id)).ToList();
                foreach (var item in list)
                {
                    await rolePermissionRepository.Delete(item.Id);
                }
                await unOfWork.SaveChanges();
            }
            return new ResponseResultDTO<int>()
            {
                Data = arr.Length,
                Message = "修改成功！",
                Code = ResultStatusCode.SUCCESS,
            };
        }
        /// <summary>
        /// 角色录入
        /// </summary>
        /// <returns></returns>
        public async Task<ResponseResultDTO<int>> PostRoleInfo(Roles entity)
        {
            var list = await rolesRepositories.GetAll();
            list=list.Where(x=>x.RoleName.Equals(entity.RoleName)).ToList();
            if (list.Count() > 0)
            {
                return new ResponseResultDTO<int>
                {
                    Code = ResultStatusCode.HANDLEFAIL,
                    Data = list.Count(),
                    Message = "角色名已存在！",//角色名已存在！
                };
            }
            
            await rolesRepositories.Add(entity);
            await unOfWork.SaveChanges();
            /*（勿删，后期有用）
            Roles roles = new Roles()
            {
                CreateName = entity.CreateName,
                CreateTime = DateTime.Now,
                Delete = entity.Delete,
                RoleDescription = entity.RoleDescription,
                Id = entity.Id,
                RoleName = entity.RoleName,
                RoleStart = entity.RoleStart,
                UpdateName = entity.UpdateName,
                UpdateTime = entity.UpdateTime,
            };
            //添加权限关系
            foreach (var item in dto.PId)
            {
                RolePermission rolePermission = new RolePermission() { PermissionId = item.PermissionId, RoleId = roles.Id };
                await rolePermissionRepository.Add(rolePermission);
            }
            */
            return new ResponseResultDTO<int>()
            {
                Data = list.Count(),
                Message = "添加成功！",
                Code = ResultStatusCode.SUCCESS,
            };
        }
    }
}
